<?php

class UsuarioController extends Controller
{
	public $layout='//layouts/column2';

	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			'postOnly + delete', // we only allow deletion via POST request
		);
	}

	public function actionVer()
	{
	
		$curriculo= Curriculo::model()->find('usuario_id='.Yii::app()->user->id);
		
		$this->render('ver',array(
			'model'=>$this->loadModel(Yii::app()->user->id),'curriculo'=>$curriculo,
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new Usuario;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Usuario']))
		{
			$model->attributes=$_POST['Usuario'];
			$model->perfil_id = 6;
			if($model->save())
				$this->redirect(array('ver','id'=>$model->id));
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionEditar()
	{
		if(Yii::app()->user->isAdmin()){
		$model=$this->loadModel('usuario_id='.Yii::app()->user->id);
		}else{
		$model=$this->loadModel(Yii::app()->user->id);
}
		if(isset($_POST[get_class($model)]))
		{
			$model->attributes=$_POST[get_class($model)];
			if($model->save(false))
				$this->redirect(array('ver','id'=>$model->id));
		}

		$this->render('editar',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		$this->loadModel($id)->delete();

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('Usuario');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Usuario('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Usuario']))
			$model->attributes=$_GET['Usuario'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return Usuario the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=Usuario::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'A página não existe.');
		return $model;
	}
  /**
     * Exibe a pagina de autenticação
     */
	 
	 	public function actionOrientacao(){
			$criteria = new CDbCriteria;
			$criteria->condition='perfil_id=3 OR perfil_id=7';
			$model = Usuario::model()->findAll($criteria);

		if(isset($_POST['selectedIds']))
        {
            foreach ($_POST['selectedIds'] as $id)
            {
				$i = 0;
				$professor = Usuario::model()->findByPk($id);
				if($professor->perfil_id == 3){
				$professor->perfil_id = 7;
				}else $professor->perfil_id = 3;
				$professor->save(false);
				$orientadores[$i] = $professor;
				
            }
			$this->redirect('orientacao',array('model'=>$model));
        }
    
				
				
				
		
	
	$this->render('orientacao',array('model'=>$model));


}	
    public function actionOrientar(){
	$criteria = new CDbCriteria;
	
	$model =  Yii::app()->db->createCommand('SELECT * FROM usuario WHERE perfil_id = 4 and id NOT IN (SELECT aluno_id FROM orientacao)')->queryAll();
	
		if(isset($_POST['selectedIds'])){
			foreach ($_POST['selectedIds'] as $id){
				$criteria->condition='professor_id='.Yii::app()->user->id.' and aluno_id='.$id;
				$orientacao = Orientacao::model()->find($criteria);
					if(!$orientacao)
						$orientacao = new Orientacao;
						$orientacao->professor_id = Yii::app()->user->id;
						$orientacao->aluno_id = $id;
						$orientacao->data_inicio = date('Y-m-d');
						$orientacao->save(false);
	}
	echo Yii::app()->user->setFlash('success', "Aluno atribuido a orientação com sucesso");
	$this->redirect('orientar',array('model'=>$model));
	}
	$this->render('orientar',array('model'=>$model));
	
	
	
	}
	
	public function actionDesfazer(){
	$criteria = new CDbcriteria;
	$model = Orientacao::model()->findAll('professor_id='.Yii::app()->user->id);
	
	if(isset($_POST['selectedIds'])){
			foreach ($_POST['selectedIds'] as $id){
				$criteria->condition='professor_id='.Yii::app()->user->id.' and aluno_id='.$id;
				$orientacao = Orientacao::model()->deleteAllByAttributes(array('aluno_id' => $id, 'professor_id'=>Yii::app()->user->id));	
	}
	echo Yii::app()->user->setFlash('success', "Orientação desfeita");
	$this->redirect('desfazer',array('model'=>$model));
	}
	
	$this->render('desfazer',array('model'=>$model));
	}

	public function actionTema() {
		if(Tema::model()->findByAttributes(array('aluno_id' => Yii::app()->user->id)))
			$model = Tema::model()->findByAttributes(array('aluno_id' => Yii::app()->user->id));
		else
			$model = new Tema;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Tema']))
		{
			$model->attributes = $_POST['Tema'];
			$model->aluno_id = Yii::app()->user->id;
			$model->save();
		}

		$this->render('tema', array(
			'model' => $model,
		));
	}
	 
	 
    public function actionEntrar()
    {
        $model = new EntrarForm();

        // if it is ajax validation request
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'entrar-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }

        // collect user input data
        if (isset($_POST['EntrarForm'])) {
            $model->attributes = $_POST['EntrarForm'];
            // validate user input and redirect to the previous page if valid
            if ($model->validate() && $model->entrar())
                $this->redirect(Yii::app()->user->returnUrl);
        }
        // display the login form
        $this->render('entrar', array('model' => $model));
    }

    /**
     * Desconecta o usuário e o redireciona para o pagina inicial
     */
	 
	
    public function actionSair()
    {
        Yii::app()->user->logout();
        $this->redirect(Yii::app()->homeUrl);
    }
	
	
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='usuario-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
        
        
        
        
}
